package mr.ali.videoapp.portal.service.impl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import mr.ali.videoapp.portal.WeChatConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class WxaCodeService {

    private static final String WXACODE_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit";

    @Autowired
    private WeChatConfig weChatConfig;

    @Autowired
    private ObjectMapper objectMapper;

    public byte[] generateWxaCodeUnlimit(String page, String scene, Integer width,
                                         Boolean autoColor, Integer r, Integer g, Integer b,
                                         Boolean isHyaline, String envVersion) throws Exception {

        // 参数校验
        if (scene == null || scene.isEmpty()) {
            throw new IllegalArgumentException("scene 参数不能为空");
        }
        if (scene.length() > 32) {
            throw new IllegalArgumentException("scene 参数不能超过 32 个字符");
        }
        if (!scene.matches("^[\\w!#$&'()*+,/:;=?@\\-.~]*$")) {
            throw new IllegalArgumentException("scene 参数包含非法字符");
        }
        if (page == null || page.isEmpty()) {
            throw new IllegalArgumentException("page 参数不能为空");
        }

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("scene", scene);
        requestBody.put("page", page);
        requestBody.put("check_path", true);
        requestBody.put("env_version", envVersion != null ? envVersion : "release");
        requestBody.put("width", width != null ? width : 430);
        requestBody.put("auto_color", autoColor != null ? autoColor : false);

        if (!autoColor) {
            Map<String, Integer> lineColor = new HashMap<>();
            lineColor.put("r", r != null ? r : 0);
            lineColor.put("g", g != null ? g : 0);
            lineColor.put("b", b != null ? b : 0);
            requestBody.put("line_color", lineColor);
        }

        requestBody.put("is_hyaline", isHyaline != null ? isHyaline : false);

        // 转 JSON
        String jsonBody;
        try {
            jsonBody = objectMapper.writeValueAsString(requestBody);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("构建请求参数失败", e);
        }

        // 发起 POST 请求
        RestTemplate restTemplate = new RestTemplate();
        String accessToken = weChatConfig.getAccessToken();
        String url = WXACODE_URL + "?access_token=" + accessToken;

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> entity = new HttpEntity<>(jsonBody, headers);

        ResponseEntity<byte[]> response = restTemplate.postForEntity(url, entity, byte[].class);

        byte[] body = response.getBody();
        if (body == null) {
            throw new RuntimeException("微信接口返回空数据");
        }

        // 判断是否为错误响应（JSON 格式）
        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> errorMap = objectMapper.readValue(body, Map.class);
            if (errorMap.containsKey("errcode") && (Integer) errorMap.get("errcode") != 0) {
                throw new RuntimeException("微信接口错误: errcode=" + errorMap.get("errcode") +
                        ", errmsg=" + errorMap.get("errmsg"));
            }
        } catch (Exception e) {
            // 不是 JSON，说明是图片流，正常情况
        }

        return body; // 返回图片二进制
    }
}